  
//
//  WXCarAroundViewController.m
//  CarJX
//
//  Created by xcq on 14-9-19.
//  Copyright (c) 2014年 KK. All rights reserved.
//

#import "WXCarAroundViewController.h"
 #import "WXCarWashTableViewCell.h"
#import "WXCarWashTableView.h"
 #import "WXPoiSearchTableViewCell.h"
#import "WXCarAroundViewController.h"
#import "CarAroundDataSource.h"
//button的大小
#define kSize  CGSizeMake(40, 40)
#define kPublishSpacing 55
#define kCarRroundSpacing -50
#define kDefaultShopPic [UIImage imageNamed:@"ios2_r1_c2_s1"]

#define kService @"service"


#define Kfindservice @"server"
#define kMainViewFrame  self.view.frame


#pragma mark - mapBar的位置(联系商家，导航的那个条)
//发布需求时bar的位置
#define kMapViewBar CGRectMake(0, 468, 320, 52)
//车周边时bar的位置
#define kMapViewBar_twoFrame CGRectMake(0, 516 , 320, 52)

//#define MYBUNDLE_NAME @ "mapapi.bundle"
//#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
//#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]


#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]

static BOOL locaiotnBol = NO;
@interface RouteAnnotation : BMKPointAnnotation
{
	int _type; ///<0:起点 1：终点 2：公交 3：地铁 4:驾乘 5:途经点
	int _degree;
}

@property (nonatomic) int type;
@property (nonatomic) int degree;
@end

@implementation RouteAnnotation

@synthesize type = _type;
@synthesize degree = _degree;

@end
@interface UIImage(InternalMethod)

- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees;

@end

@implementation UIImage(InternalMethod)

- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees
{
    
    CGFloat width = CGImageGetWidth(self.CGImage);
    CGFloat height = CGImageGetHeight(self.CGImage);
    
	CGSize rotatedSize;
    
    rotatedSize.width = width;
    rotatedSize.height = height;
    
	UIGraphicsBeginImageContext(rotatedSize);
	CGContextRef bitmap = UIGraphicsGetCurrentContext();
	CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
	CGContextRotateCTM(bitmap, degrees * M_PI / 180);
	CGContextRotateCTM(bitmap, M_PI);
	CGContextScaleCTM(bitmap, -1.0, 1.0);
	CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
	UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
}

@end

@interface WXCarAroundViewController () <UIAlertViewDelegate,UIActionSheetDelegate,BMKPoiSearchDelegate>
{
    NSString *ID;
    NSMutableArray *customServer;
    NSArray *storeArray;
    CarAroundDataSource *carAround;
    NSMutableArray *coordinateArray;
    WXCarWashTableView *carWashtableView;
    WXCarWashTableView *poiSearchTabelView;
    UIView *moban;
    int addSubMapBar ;
    UIButton *rightBtn;
    NSMutableArray *annotionArray;
    NSDictionary *mapBarDetailDic;
    BMKCircle*  circle;   //绘制我得位置这个圈
    BMKPoiSearch *_poisearch;  //周边搜索
    NSArray* poiInfoList;   //周边搜索到得点得详细信息
    NSString *poiPhone;   //周边搜索出来的电话
    UIButton *_daoHangBtn;   //导航按钮
}

@end
static BOOL firstLocation = YES;
static NSString *seleteKey = @"all";
static NSString *seleteOneKey;
static NSString *seleteDistance;
static bool isZhouBianFuWu;    //区别是周边搜索要加点还是服务洗车类型加点
static NSString *poiKeyString; //周边搜索的关键字

//发布需求的选择项
static NSString *releaseRequert;


  // jzxc  洗车     weixiu  维修   upkeep 保养

@implementation WXCarAroundViewController

-(void) viewDidAppear:(BOOL)animated
{
//    NSString* cName = [NSString stringWithFormat:@"%@",  self.navigationItem.title, nil];
//    [[BaiduMobStat defaultStat] pageviewStartWithName:cName];
    
}

-(void) viewDidDisappear:(BOOL)animated
{
//    NSString* cName = [NSString stringWithFormat:@"%@", self.navigationItem.title, nil];
//    [[BaiduMobStat defaultStat] pageviewEndWithName:cName];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}


- (NSString*)getMyBundlePath1:(NSString *)filename
{
	
	NSBundle * libBundle = MYBUNDLE ;
	if ( libBundle && filename ){
		NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
 		return s;
	}
 	return nil ;
}
- (void) viewWillAppear:(BOOL)animated{
    
    if (_mapView == nil && _location == nil) {
        return;
    }else{
        _routesearch.delegate = self;
        _mapView.delegate = self;
        _location.delegate = self;
        _poisearch.delegate = self;
        [_location startLocation];
        _mapView.showsUserLocation = NO;
        _mapView.userTrackingMode = BMKUserTrackingModeFollow;
        _mapView.showsUserLocation = YES;
        
    }
}

-(void) viewWillDisappear:(BOOL)animated{
    [_mapView viewWillDisappear];
    [_location stopLocation];
    _location.delegate = nil;
    _mapView.delegate = nil;
    _routesearch.delegate = nil;
    _poisearch.delegate = nil;

}

- (void)backTo{
    if ([_keyString1 isEqualToString:@"root"]) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (instancetype)initWithNSString:(NSString *)keyStr{
    self = [super init];
    if (self) {
        self.keyString1 = keyStr;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view makeToastActivity];
    circle = nil;
    addSubMapBar = 0;
    moban = [[UIView alloc] initWithFrame:self.view.frame];
    moban.backgroundColor = [UIColor whiteColor];
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        self.locationManager = [[CLLocationManager alloc] init];
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager requestWhenInUseAuthorization];
    }

    [self initNavigation];
 
  
    poiSearchTabelView = [[WXCarWashTableView alloc] initWithFrame:CGRectMake(0, 0, kMainViewFrame.size.width, kMainViewFrame.size.height) style:UITableViewStylePlain];
    
    [poiSearchTabelView registerNib:[UINib nibWithNibName:@"WXPoiSearchTableViewCell" bundle:nil] forCellReuseIdentifier:PoiSearchTabelViewCell];
    poiSearchTabelView.delegate = self;
    poiSearchTabelView.dataSource = self;
    [moban addSubview:poiSearchTabelView];
    [self.view addSubview:moban];
    [self.view sendSubviewToBack:moban];
    serverChange.backgroundColor = UICOLOR_MAKE_RGB(240, 240, 240);
    distanceChange.backgroundColor = UICOLOR_MAKE_RGB(240, 240, 240);
    customServer = [[NSMutableArray alloc] init];
  
     //地图初始化
    [self initMapView];
 
    _mapViewBar.hidden = YES;

#pragma mark - 如果是车周边，定位按钮就会随着mapBar的出现和隐藏而改变位置
    location = [[UIButton alloc] initWithFrame:(CGRect){ {15,_mapViewBar.frame.origin.y + kCarRroundSpacing} , kSize }];
    _daoHangBtn = [[UIButton alloc] initWithFrame:(CGRect){ {15,_mapViewBar.frame.origin.y + 2*kCarRroundSpacing-10 }  , kSize}];
    _daoHangBtn.hidden = YES;

    originalLocation = location.frame;
      [location addTarget:self action:@selector(locationBtn) forControlEvents:UIControlEventTouchUpInside];
  //  [_neiMuBtn addTarget:self action:@selector(neiMuClick) forControlEvents:UIControlEventTouchUpInside];
    [_daoHangBtn addTarget:self action:@selector(CheckDetails:) forControlEvents:UIControlEventTouchUpInside];
    //搜索初始化
    [_mapViewBar setBackgroundColor:[UIColor whiteColor]];
    [location setBackgroundImage:[UIImage imageNamed:@"huiyuandian"] forState:UIControlStateNormal];
  //  [_neiMuBtn setBackgroundImage:[UIImage imageNamed:@"zhoubian"] forState:UIControlStateNormal];
    [_daoHangBtn setBackgroundImage:[UIImage imageNamed:@"go_to_there_bg"] forState:UIControlStateNormal];

    [self.view addSubview:location];
     [self.view addSubview:_daoHangBtn];
    [self initLocationSearch];

}

- (void)initNavigation {
    self.title = self.Navtitle;

    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setBackgroundImage:[UIImage imageNamed:BACKIMAGE] forState:UIControlStateNormal];
    leftBtn.frame = CGRectMake(0,
                               kNavigationBtnSpaceHorizontal,
                               kNavigationBtnHeight * [UIImage imageNamed:BACKIMAGE].size.width / [UIImage imageNamed:BACKIMAGE].size.height,
                               kNavigationBtnHeight);
    [leftBtn addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBar;
    
    rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setFrame:(CGRect){leftBtn.frame.origin ,{ leftBtn.frame.size.width + 15 , leftBtn.frame.size.height}}];
    [rightBtn setTitle:@"列表" forState:UIControlStateNormal];
    rightBtn.titleLabel.textColor = [UIColor whiteColor];
    [rightBtn addTarget:self action:@selector(MapClick:) forControlEvents:UIControlEventTouchUpInside];
      self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
 }

#pragma mark - 定位按钮事件
-(void) locationBtn{
    
    locaiotnBol = YES;
    [self  startLocation];
}
#pragma mark - 类目按钮事件 和 周边搜索
-(void)neiMuClick{
//   
//    WXCategoryViewController *category = [[WXCategoryViewController alloc] init];
// 
//    category.callBack = ^(NSString *keyString){  //百度周边
//        NSLog(@"点击了%@",keyString);
//        [self findArouldSerViceWithKey:keyString];
//        self.serverType = @"周边搜索";
//    };
//    category.callBack2 = ^(NSString *serverType,NSString *title){   //一级类目点击事件
//        seleteOneKey = serverType;
//        [self setNavtitle:title];
//        [self findServer];
//    
//    };
//    [self.navigationController pushViewController:category animated:YES];
}

- (void)BmkPoiSearch{
    [self findArouldSerViceWithKey:_keyWord];
    self.serverType = @"周边搜索";
}

- (void)muneClickAction:(NSString *)serverType andTitle:(NSString *)title {
    seleteOneKey = serverType;
    self.Navtitle = title;
    self.title = self.Navtitle;
    [self findServer];
}


#pragma mark - poi搜索
-(void)findArouldSerViceWithKey:(NSString *)keyString;
{
    //搜周边
    poiKeyString = keyString;
    BMKNearbySearchOption *nearSearch = [[BMKNearbySearchOption alloc] init];
    nearSearch.keyword = keyString;
    nearSearch.location = _coordinate;
    nearSearch.radius = 100000;
    nearSearch.pageIndex = 0;
    nearSearch.pageCapacity = 40;
    BOOL flag = [_poisearch poiSearchNearBy:nearSearch];
    if(flag)
    {
        NSLog(@"城市内检索发送成功");
    }
    else
    {
        NSLog(@"城市内检索发送失败");
    }
    [self.view hideToastActivity];
    isZhouBianFuWu = YES;
}
- (void)setNavtitle:(NSString *)Navtitle{
    if (Navtitle) {
        _Navtitle = Navtitle;
        self.title = _Navtitle;
    }
}

#pragma mark - WXReleaseRequest
- (void) releaseRequest:(NSNotification *)sender{
    
   // WXGeneratOrderViewController *generat = sender.object;
//    [self presentViewController:generat animated:YES completion:nil];
  //  [self.navigationController pushViewController:generat animated:YES];
    
 }

#pragma mark  - 地图列表切换按钮
-(void)MapClick:(id)sender
{
    
    if (!poiSearchTabelView.isfront) {
        [self.view bringSubviewToFront:moban];
        [moban bringSubviewToFront:poiSearchTabelView];
         poiSearchTabelView.isfront = YES;
        [rightBtn setTitle:@"地图" forState:UIControlStateNormal];
    }else{
        [self.view sendSubviewToBack:moban];
        poiSearchTabelView.isfront = NO;
        [rightBtn setTitle:@"列表" forState:UIControlStateNormal];
    }
    
}


#pragma mark - 初始化地图
- (void) initMapView{
    
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, _backView.frame.size.width, _backView.frame.size.height)];
    _mapView.mapType = BMKMapTypeStandard;
    
    [_mapView setDelegate:self];
//    _mapView.zoomLevel = 19.0f;
    [_mapView setZoomLevel:13];  //设置地图的缩放级别
    
    [_backView addSubview: _mapView];
    [_backView sendSubviewToBack:_mapView];
    _poisearch = [[BMKPoiSearch alloc]init];  //周边搜索初始化

//    if ([_keyString1 isEqualToString:@"root"]) {
//        [self.view bringSubviewToFront:moban];
//        [rightBtn setTitle:@"地图" forState:UIControlStateNormal];
//    }
}

#pragma mark - 开始定位
- (void) startLocation{
    _coordinate.latitude = 0;
    _coordinate.longitude = 0;
    if (!self.locService) {
        self.locService = [[LocationGetObj alloc] init];
    }
    self.locService.delegate = self;
    [self.locService startLocation];
    firstLocation = NO;

}

- (void) initLocationSearch{
    if (!_location) {
     _location = [[LocationGetObj alloc] init];
     _location.delegate = self;
    }
    [_location startLocation];
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;
    
}
- (void) stopUserLocation{
    [_location stopLocation];
}



- (void) serverDataDispose{
    if (coordinateArray == nil) {
        coordinateArray = [[NSMutableArray alloc] initWithCapacity:[customServer count]];
    }
    //数据处理完，加载地图标点
    [self addMkPointWithMap];
}

#pragma mark - 定位成功
- (void)getLocationSuccess:(BMKUserLocation *)userLocation{
    
//    if (_coordinate.latitude == 0 && _coordinate.longitude == 0) {
//        firstLocation = NO;
        _coordinate = userLocation.location.coordinate;
   
        if (point2) {
            return;
        }else{
             point2 = [[MapPointAnnotion alloc] init];
            point2.id_shop = @"location";
            point2.tag = 500;
            point2.coordinate = _coordinate;
            point2.title = @"我的位置";
            [_mapView addAnnotation:point2];
        }
       // [_mapView addAnnotation:point];
        [_mapView setRegion:BMKCoordinateRegionMake(userLocation.location.coordinate, BMKCoordinateSpanMake(0.09, 0.09)) animated:YES];
        if (locaiotnBol) {
            locaiotnBol = NO;
        }else{
            [self getAddress];
            NSArray *array = @[[NSString stringWithFormat:@"%f",_coordinate.latitude ] , [NSString stringWithFormat:@"%f",_coordinate.longitude] ];
            [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"coordinate"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
         //如果是外面美食传进来的 return 不在加洗车等服务类型的点
           [self findArouldSerViceWithKey:_keyWord];   //周边搜索
          //  [self stopUserLocation];
            // return;
     [self.view hideToastActivity];
}


//114.411191
//30.507851

#pragma mark - 定位成功就请求周边店铺信息
- (void) findServerWithtype{
    if (!carAround) {
        carAround = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    if (_coordinate.longitude == 0 && _coordinate.latitude == 0) {
        [_location startLocation];
    } else{
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSString stringWithFormat:@"%.7f",_coordinate.latitude],@"lat",
                             [NSString stringWithFormat:@"%.7f",_coordinate.longitude],@"lon",
                             @"server",@"dic_type",
                             seleteDistance,@"distance",
                             self.serverType,@"dic_name",
                             nil];
        [self.navigationController.view makeToastActivity:TOP_POINT];
        //TODO:请求周边店铺信息
//        [self GETWithContentType:@"findservice" params:dic success:^(Result *result) {
//            [self.navigationController.view hideToastActivity];
//            customServer = result.dictionaryInfo[@"server"];
//            [self serverDataDispose];
//            
//            [carWashtableView reloadData];
//        } failure:^(NSError *error) {
//             [self.navigationController.view hideToastActivity];
////            [self.view makeToast:@"加载失败" duration:1 position:TOP_POINT];
//        }];
//    }
    }
    
}

- (void) findServer{
    
    if (_coordinate.longitude == 0 && _coordinate.latitude == 0) {
        [_location startLocation];
    } else{
        //TODO:服务搜索
        //        [self GETWithContentType:@"findservice" params:@{@"lat" : [NSString stringWithFormat:@"%.7f",_coordinate.latitude], @"lon" : [NSString stringWithFormat:@"%.7f",_coordinate.longitude], @"dic_name" : seleteOneKey , @"dic_type" : @"server" , @"distance" : seleteDistance} success:^(Result *result) {
        //            [self.view hideToastActivity];
        //            customServer = result.dictionaryInfo[@"server"];
        //             [self serverDataDispose];
        //            [carWashtableView reloadData];
        //
        //        } failure:^(NSError *error) {
        //            NSLog(@"%@",error.localizedDescription);
        //         }];
        
    }
    
    //预防多个指示器转动
    [self.view hideToastActivity];
    [self.view makeToastActivity:TOP_POINT  ];
}

#pragma mark - 地图区域改变完成后会调用此接口
//- (void) mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
//    if (isZhouBianFuWu) { //如果是搜索周边就直接返回
//        return;
//    }
//    if ([self.serverType isEqualToString:@"路救"]) {   //如果是路救过来的，就直接返回
//        return;
//    }
//    if (firstLocation == NO) {
//        firstLocation = YES;
//        return;
//    }
//    if ([self.Navtitle isEqualToString:@"车周边"]) {
//        
//        if (seleteOneKey) {
//            seleteKey = seleteOneKey;
//        }else {
//            seleteKey = @"all";
//        }
//    }
//    if ([self.Navtitle isEqualToString:@"维修"]) {
//        if (seleteOneKey) {
//            seleteKey = seleteOneKey;
//        }else {
//            seleteKey = @"weixiu";
//        }
//     }
//    if ([self.Navtitle isEqualToString:@"保养"]) {
//        if (seleteOneKey) {
//            seleteKey = seleteOneKey;
//        }else {
//            seleteKey = @"upkeep";
//        }
//        
//     }
//    if ([self.Navtitle isEqualToString:@"洗车"]) {
//        if (seleteOneKey) {
//            seleteKey = seleteOneKey;
//        }else {
//            seleteKey = @"jzxc";
//        }
//       
//     }
//    if([self.Navtitle isEqualToString:@"美容"]){
//
//        if (seleteOneKey) {
//            seleteKey = seleteOneKey;
//        }else {
//            seleteKey = @"hairdressing";
//        }
//    }
//     _coordinate = mapView.centerCoordinate;
//    
//    NSLog(@"%@",seleteKey);
//    
//    [self GETWithContentType:@"findservice" params:@{@"lat" : [NSString stringWithFormat:@"%.7f",_coordinate.latitude], @"lon" : [NSString stringWithFormat:@"%.7f",_coordinate.longitude], @"dic_name" : seleteKey , @"dic_type" : @"server" , @"distance" : seleteDistance} success:^(Result *result) {
//            [self.navigationController.view hideToastActivity];
//            customServer = result.dictionaryInfo[@"server"];
//            [self serverDataDispose];
//            
//        } failure:^(NSError *error) {
//            NSLog(@"%@",error.localizedDescription);
//        }];}

#pragma mark - 自定义标注图片
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[RouteAnnotation class]]) {
         return [self getRouteAnnotationView:mapView viewForAnnotation:(RouteAnnotation*)annotation];
    }
    
    MapAnnotationView *annotationView =(MapAnnotationView*)[mapView viewForAnnotation:annotation];
    
    if (annotationView==nil&&[annotation isKindOfClass:[MapPointAnnotion class]])
    {
        MapPointAnnotion* pointAnnotation=(MapPointAnnotion*)annotation;
        NSString *AnnotationViewID = [NSString stringWithFormat:@"iAnnotation-%i",pointAnnotation.tag];
		annotationView = [[MapAnnotationView alloc] initWithAnnotation:annotation      reuseIdentifier:AnnotationViewID];
        /*
         装饰 :  decorate
         保养 :  upkeep
         美容 : hairdressing
         维修 : weixiu
         洗车：  jzxc
         */
        
        NSLog(@"%@",pointAnnotation.id_shop);
        if ([[pointAnnotation id_shop] isEqualToString:@"decorate"])
        {
            annotationView.image = [UIImage imageNamed:@"11_22"];
        }else if ([[pointAnnotation id_shop] isEqualToString:@"all"]){ //11_19@2x
            annotationView.image = [UIImage imageNamed:@"11_22"];
        }else if([[pointAnnotation id_shop] isEqualToString:@"upkeep"]){
            annotationView.image = [UIImage imageNamed:@"11_27"];
            
        }else if([[pointAnnotation id_shop] isEqualToString:@"jzxc"]){
            annotationView.image = [UIImage imageNamed:@"11_14"];
            
        }else if([[pointAnnotation id_shop] isEqualToString:@"hairdressing"]){
            annotationView.image = [UIImage imageNamed:@"11_22"];
        }else if([[pointAnnotation id_shop] isEqualToString:@"weixiu"]){
            annotationView.image = [UIImage imageNamed:@"11_11"];
            
        }else if([[pointAnnotation id_shop] isEqualToString:@"location"]) {
            annotationView.image = [UIImage imageNamed:@"myLocation"];
            if (circle == nil) {
                circle = [BMKCircle circleWithCenterCoordinate:_coordinate radius:3000];
                [_mapView addOverlay:circle];
            }

        }else{
            annotationView.image = [UIImage imageNamed:@"11_22"];
            
        }
 
        annotationView.tag=pointAnnotation.tag;
//        if (pointAnnotation.tag == 399) {
//            annotationView.image = [UIImage imageNamed:@"icon_center_point"];
//        }
    }
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    
    annotationView.canShowCallout = TRUE;
    return annotationView ;
}
#pragma mark 周边搜索代理
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    poiInfoList = result.poiInfoList;
    [poiSearchTabelView reloadData];
    
  // 清除屏幕中所有的annotation 除了我得位置
    NSMutableArray* array = [NSMutableArray arrayWithArray:_mapView.annotations];
    for (MapPointAnnotion *annotation in array) {
        if ([annotation.id_shop isEqualToString:@"location"]) {
            [array removeObject:annotation];
            break;
        }
    }
	[_mapView removeAnnotations:array];
    
    if (error == BMK_SEARCH_NO_ERROR) {
		for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            [_mapView addAnnotation:item];
            if(i == 0)
            {
                //将第一个点的坐标移到屏幕中央
                _mapView.centerCoordinate = poi.pt;
            }
		}
	} else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
     } else {
        // 各种情况的判断。。。
    }
}
#pragma mark -根据overlay生成对应的View
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay
{
	if ([overlay isKindOfClass:[BMKCircle class]])   //绘制我的位置
    {
        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay] ;
        circleView.fillColor = UICOLOR_MAKE_RGB_A(61, 89, 171, 0.5);
		return circleView;
    }
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay]  ;
        polylineView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:1];
        polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        polylineView.lineWidth = 2.0;
        return polylineView;
    }
	return nil;
    
}

#pragma mark - 这里的和下面的touchesBegan方法都是为了在点击地图后隐藏mapBar，和改变定位的位置～originalLocation是一个成员变量，记录定位按钮在车周边或者发布需求里初始化的位置，用于将定位的位置重置为初始值
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate{
 
    location.frame = originalLocation;
    _daoHangBtn.frame = originalLocationDaoHang;
        _mapViewBar.hidden = YES;
    if (carAddresPoint && [carAddresPoint count ] > 0) {
        [_mapView removeAnnotations:carAddresPoint];
        [_mapView removeOverlay:polyLine];
    }
}
 
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    _mapViewBar.hidden = YES;
    location.frame = originalLocation;
     _daoHangBtn.frame = originalLocationDaoHang;

    if (carAddresPoint && [carAddresPoint count ] > 0) {
        [_mapView removeAnnotations:carAddresPoint];
        [_mapView removeOverlay:polyLine];
    }
}

#pragma mark - 泡泡的点击事件
- (void) mapView:(BMKMapView *)mapView annotationViewForBubble:
(BMKAnnotationView *)view{
    if (view.tag == 500) {
        return;
        
    }
    if (isZhouBianFuWu) {   //如果是百度poi搜索出来得点就直接返回
        return;
    }
//    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    CLUIBaseNavigationController *shop = [story instantiateViewControllerWithIdentifier:@"ShopOne"];
//    if ([self.serverType isEqualToString:@"路救"]) {
//        shop.identity = @"路救";
//    }else{
//        shop.identity = @"车周边";
//#warning 这里也是一样的，只有店铺坐标，没有距离
//    }
//    for (MapPointAnnotion *point1  in  annotionArray) {
//        if (point1.tag == view.tag) {
//            shop.shopInfo = point1.info;
//            break;
//        }
//        
//    }
//    shop.ID = [[NSNumber numberWithInteger:view.tag] stringValue];
//    
//    [self.navigationController pushViewController:shop animated:YES];
//    
}

#pragma mark 点击标注
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    if (view.tag == 500) {
        return;
    }
    location.frame = (CGRect) { {15,_mapViewBar.frame.origin.y - 50 },kSize} ;
//    _neiMuBtn.frame = (CGRect) { {15,_mapViewBar.frame.origin.y - 100 },kSize} ;
    _daoHangBtn.frame = (CGRect) { {15,_mapViewBar.frame.origin.y - 100 },kSize} ;
    
    if (isZhouBianFuWu) {  //如果是周边搜索
        _roundSearchCoor = view.annotation.coordinate;  //为了导航
        for (BMKPoiInfo *info in poiInfoList) {
            if (info.pt.latitude == _roundSearchCoor.latitude) {
                poiPhone = info.phone;
                break;
            }
        }
     }
    _mapViewBar.hidden = NO;
    for (MapPointAnnotion *point1  in  annotionArray) {
        if (point1.tag == view.tag) {
            _shopDetail.text = point1.title;
            mapBarDetailDic = point1.info;  //  联系商家
            _roundSearchCoor = point1.coordinate;    //导航
            break;
        }
    }
 }


#pragma mark - 地图加标注
- (void) addMkPointWithMap{
    
    if (annotionArray == nil) {
        annotionArray = [[NSMutableArray alloc] init];
    }
    if([annotionArray count] > 0){
        [_mapView removeAnnotations:annotionArray];
        [annotionArray removeAllObjects];
    }
    NSMutableArray* array = [NSMutableArray arrayWithArray:_mapView.annotations];
    for (MapPointAnnotion *annotation in array) {
        if ([annotation.id_shop isEqualToString:@"location"]) {
            [array removeObject:annotation];
            break;
        }
    }
	[_mapView removeAnnotations:array];

    int i = 0;
    
    for (NSDictionary *dic in  customServer) {
        CLLocationCoordinate2D coor = CLLocationCoordinate2DMake([[dic objectForKey:@"LAT"] doubleValue], [[dic objectForKey:@"LON"] doubleValue]);
        MapPointAnnotion *point1 = [[MapPointAnnotion alloc]init];
        point1.coordinate = coor;
        point1.info = dic;
        point1.id_shop = (self.serverType == nil ? seleteOneKey:self.serverType);
        point1.title = ([dic objectForKey:@"SHOP_NAME"]!= [NSNull null])?[dic objectForKey:@"SHOP_NAME"]  : @"" ;
        point1.tag = [[dic objectForKey:@"ID"] intValue];
        [annotionArray addObject:point1];
        
        i ++;
        
    }
    [_mapView addAnnotations:annotionArray];
    isZhouBianFuWu = NO;
    
    
}

- (void) getAddress{
    
    CLLocation *c = [[CLLocation alloc] initWithLatitude:_coordinate.latitude longitude:_coordinate.longitude];
    //创建位置
    CLGeocoder *revGeo = [[CLGeocoder alloc] init];
    [revGeo reverseGeocodeLocation:c
                  completionHandler:^(NSArray *placemarks, NSError *error) {
                     if (!error && [placemarks count] > 0)
                     {
                         NSDictionary *dict =
                         [[placemarks objectAtIndex:0] addressDictionary];
                         
                         NSString *str = [dict objectForKey:@"City"];
                         
                         [[NSUserDefaults standardUserDefaults] setObject:str forKey:@"systemAddress"];
                         [[NSUserDefaults standardUserDefaults] synchronize];
                     }
                     else
                     {
                         NSLog(@"ERROR: %@", error); }  
                 }];
    
}

#pragma mark - table delege
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == carWashtableView) {
        if (customServer) {
            return customServer.count;
        }
    }else if(tableView == poiSearchTabelView){
        return poiInfoList.count;
    }
    
        return 0;
}

- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == carWashtableView) {
        static NSString *CellIdentifier = @"UISpecialTableViewCell";
        WXCarWashTableViewCell *cell = (WXCarWashTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        if (cell == nil)
        {
            cell= (WXCarWashTableViewCell *)[[[NSBundle  mainBundle]  loadNibNamed:@"WXCarWashTableViewCell" owner:self options:nil]  lastObject];
        }
        // 自己的一些设置
        NSLog(@"%@",NSStringFromCGRect(tableView.frame));
        
        //SHOP_LOGO
        NSString *imageStr =  customServer[indexPath.row][@"SHOP_LOGO"];
        if ([imageStr isEqual:[NSNull null]]) {
            cell.BusinessImage.image = kDefaultShopPic;
        }else{
            [cell.BusinessImage  setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:kDefaultShopPic];
            
        }
        cell.storeNameLabel.text = customServer[indexPath.row][@"SHOP_NAME"] != [NSNull null] ? customServer[indexPath.row][@"SHOP_NAME"] : @"";
        cell.storeAddress.text = customServer[indexPath.row][@"SHOP_ADDR"] != [NSNull null] ? customServer[indexPath.row][@"SHOP_ADDR"]  : @"" ;
        if ([self.serverType isEqualToString:@"路救"]) {
            cell.storeDistance.text = [NSString stringWithFormat:@"距离我  %@米",customServer[indexPath.row][@"distance"]];

        }else{
            cell.storeDistance.text = [NSString stringWithFormat:@"距离我  %@米",customServer[indexPath.row][@"SFZ"]];
        }
        
        return cell;
    }else if (tableView == poiSearchTabelView){
        WXPoiSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PoiSearchTabelViewCell forIndexPath:indexPath];
        [cell initPoiSearchTableViewCellInfo:poiInfoList[indexPath.row] withTarget:self contectSel:@selector(lianXiShangJia:) goHereSel:@selector(quNaEr:)];
        return cell;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == carWashtableView) {
//      //  UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//        WXShopOneTableViewController *shop = [story instantiateViewControllerWithIdentifier:@"ShopOne"];
//        shop.ID = customServer[indexPath.row][@"ID"];
//        shop.shopInfo = customServer[indexPath.row];
//        if ([self.serverType isEqualToString:@"路救"]) {
//            shop.identity = @"路救";
//        }else{
//            shop.identity = @"车周边";
//        }
//        [self.navigationController pushViewController:shop animated:YES];
    } else if (tableView == poiSearchTabelView){
        
    
    }
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == carWashtableView ) {
         return 100;
    }else if (tableView == poiSearchTabelView){
        return 144;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    return [[UIView alloc] init];
}



- (void) login{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还未登录,请先登陆" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
  
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
    //跳转到登录
//        WXBaseNavigationController *nav = [[WXBaseNavigationController alloc]  initWithRootViewController:[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"login"] andLoginStatus:YES];
//        [self presentViewController:nav animated:YES completion:^{
//            
//        }];
    }
} 


#pragma mark 商家详情
- (IBAction)mapBarBtn_one:(id)sender {
    if (isZhouBianFuWu) {
        [self.view makeToast:@"暂无详情"];
        return;
    }
    //TODO:进入商铺
//    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    WXShopOneTableViewController *shop = [story instantiateViewControllerWithIdentifier:@"ShopOne"];
//    shop.ID = [mapBarDetailDic objectForKey:@"ID"];
//    shop.shopInfo = mapBarDetailDic;
//    if ([self.serverType isEqualToString:@"路救"]) {
//        shop.identity = @"路救";
//    }else{
//        shop.identity = @"车周边";
//#warning 这里传过来的是店铺坐标点，没有传距离  联系李敬臣
//    }
//  
//    [self.navigationController pushViewController:shop animated:YES];
}

#pragma mark 联系商家
- (IBAction)mapBarBtn_two:(id)sender {

    UIWebView*callWebview =[[UIWebView alloc] init] ;
    
    if (isZhouBianFuWu) {  //如果是poi搜索
        if (poiPhone) {
            if ([poiPhone hasPrefix:@"("]) {
                NSString *substr = [poiPhone substringFromIndex:5];
                NSString *substr2 = [poiPhone substringToIndex:4];
                NSString *subStr3 = [substr2 substringFromIndex:1];
                sender = [subStr3 stringByAppendingString:substr];
            }
            NSString *tele = [@"tel://" stringByAppendingString:poiPhone];
            NSURL *telURL =[NSURL URLWithString:tele];
            [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
            [self.view addSubview:callWebview];
        }else{
            [self.view makeToast:@"暂无电话"];
        }

    }else{    // 车联自带
        NSString *phone = [mapBarDetailDic objectForKey:@"TELONE"] ;
        // tel:  或者 tel://
        if (phone) {
            NSString *tele = [@"tel://" stringByAppendingString:phone];
            NSURL *telURL =[NSURL URLWithString:tele];
            [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
            [self.view addSubview:callWebview];
        }
    }
}

#pragma mark - 导航详情
- (IBAction)CheckDetails:(id)sender {
    if (!ViaPoint) {
        return;
    }
    WXAddressDetailViewController *address = [[WXAddressDetailViewController alloc] init];
    [address setDateSource:ViaPoint];
    [address initTableView];
   [self.navigationController pushViewController:address animated:YES];
}
#pragma mark 查路线
- (IBAction)mapBarBtn_four:(id)sender {
    if (!_routesearch) {
        _routesearch = [[BMKRouteSearch alloc] init];
        _routesearch.delegate = self;
        
    }
    
	BMKPlanNode* start = [[BMKPlanNode alloc]init];
    start.pt = point.coordinate;
      start.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"systemAddress"];
	BMKPlanNode* end = [[BMKPlanNode alloc]init] ;
    end.pt = _roundSearchCoor;
     end.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"systemAddress"];
    
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = start;
    drivingRouteSearchOption.to = end;
    BOOL flag = [_routesearch drivingSearch:drivingRouteSearchOption];
     if(flag)
    {
        NSLog(@"car检索发送成功");
        _daoHangBtn.hidden = NO;
        [self.view makeToastActivity];
    }
    else
    {
        NSLog(@"car检索发送失败");
    }
}

#pragma mark - poi联系商家
-(void)lianXiShangJia:(NSString*)sender{
    NSLog(@"%@",sender);
    UIWebView*callWebview =[[UIWebView alloc] init] ;
    if (sender) {
        if ([sender hasPrefix:@"("]) {
            NSString *substr = [sender substringFromIndex:5];
            NSString *substr2 = [sender substringToIndex:4];
            NSString *subStr3 = [substr2 substringFromIndex:1];
            sender = [subStr3 stringByAppendingString:substr];
        }
        NSString *tele = [@"tel://" stringByAppendingString:sender];
        NSURL *telURL =[NSURL URLWithString:tele];
        [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
        [self.view addSubview:callWebview];
    }else{
        [self.view makeToast:@"暂无电话"];
    }

    
}
#pragma mark -  poi去那儿
-(void)quNaEr:(NSValue *)sender{

    CLLocationCoordinate2D pt;
    [sender getValue:&pt];
    NSLog(@"%@",sender);
    if (!_routesearch) {
        
        _routesearch = [[BMKRouteSearch alloc] init];
        _routesearch.delegate = self;
        
    }
    
	BMKPlanNode* start = [[BMKPlanNode alloc]init];
    start.pt = point.coordinate;
    start.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"systemAddress"];
	BMKPlanNode* end = [[BMKPlanNode alloc]init] ;
    end.pt = pt;
    end.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"systemAddress"];
    
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = start;
    drivingRouteSearchOption.to = end;
    BOOL flag = [_routesearch drivingSearch:drivingRouteSearchOption];
    if(flag)
    {
        NSLog(@"car检索发送成功");
        [self.view sendSubviewToBack:moban];
        poiSearchTabelView.isfront = NO;
        _daoHangBtn.hidden = NO;
        self.navigationItem.rightBarButtonItem.title = @"列表";
        [self.view makeToastActivity];
    }
    else
    {
        NSLog(@"car检索发送失败");
    }

}
- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    if (!carAddresPoint) {
        carAddresPoint = [[NSMutableArray alloc] init];
    }
    if ([carAddresPoint count ] > 0) {
        [_mapView removeAnnotations:carAddresPoint];
    }
    
    // [_mapView removeAnnotations:annotionArray];
 
	 NSArray*array = [NSArray arrayWithArray:_mapView.overlays];
	[_mapView removeOverlays:array];
	if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        
        // 计算路线方案中的路段数目
		int size = [plan.steps count];
        ViaPoint = [NSArray arrayWithArray: plan.steps];
		int planPointCounts = 0;
		for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                 item.type = 0;
                [carAddresPoint addObject:item];

                [_mapView addAnnotation:item]; // 添加起点标注
               
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                 item.type = 1;
                [carAddresPoint addObject:item];

                [_mapView addAnnotation:item]; // 添加起点标注
               
            }
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
             item.degree = transitStep.direction * 30;
            item.type = 4;
            [carAddresPoint addObject:item];
            [_mapView addAnnotation:item];
            
           
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                [carAddresPoint addObject:item];
                 [_mapView addAnnotation:item];
               
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
		polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
 		[_mapView addOverlay:polyLine]; // 添加路线overlay
		delete []temppoints;
        
		
	}
    [self.view hideToastActivity];
//    _checkDetailBtn.hidden = NO;

}


- (BMKAnnotationView*)getRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(RouteAnnotation*)routeAnnotation
{
	BMKAnnotationView* view = nil;
	switch (routeAnnotation.type) {
		case 0:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"];
			if (view == nil) {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"start_node"] ;
				view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_start.png"]];
				view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
				view.canShowCallout = TRUE;
			}
			view.annotation = routeAnnotation;
		}
			break;
		case 1:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"];
			if (view == nil) {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"end_node"] ;
				view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_end.png"]];
				view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
				view.canShowCallout = TRUE;
			}
			view.annotation = routeAnnotation;
		}
			break;
		case 2:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"bus_node"];
			if (view == nil) {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"bus_node"] ;
				view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_bus.png"]];
				view.canShowCallout = TRUE;
			}
			view.annotation = routeAnnotation;
		}
			break;
		case 3:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"rail_node"];
			if (view == nil) {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"rail_node"]  ;
				view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_rail.png"]];
				view.canShowCallout = TRUE;
			}
			view.annotation = routeAnnotation;
		}
			break;
		case 4:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
			if (view == nil) {
				view =  [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"]  ;
				view.canShowCallout = TRUE;
			} else {
				[view setNeedsDisplay];
			}
			
			UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_direction.png"]];
			view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
			view.annotation = routeAnnotation;
			
		}
			break;
        case 5:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"waypoint_node"];
			if (view == nil) {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"waypoint_node"] ;
				view.canShowCallout = TRUE;
			} else {
				[view setNeedsDisplay];
			}
			
			UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_waypoint.png"]];
			view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
			view.annotation = routeAnnotation;
        }
            break;
		default:
			break;
	}
	
	return view;
}

@end
